package com.game.backend.service.impl.user.account;

import com.game.backend.common.BusinessException;
import com.game.backend.mapper.UserMapper;
import com.game.backend.model.User;
import com.game.backend.service.user.account.RegisterService;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void register(String username, String password, String confirmedPassword) {
        username = username.trim();
        if(!StringUtils.hasLength(username)){
            throw new BusinessException("用户名不能为空");
        }
        if(!StringUtils.hasLength(password) || !StringUtils.hasLength(confirmedPassword)){
            throw new BusinessException("密码不能为空");
        }
        if(username.length() > 100){
            throw new BusinessException("用户名长度不能大于100");
        }
        if(password.length() > 100 || confirmedPassword.length() > 100){
            throw new BusinessException("密码长度不能大于100");
        }
        if(!password.equals(confirmedPassword)){
            throw new BusinessException("两次密码不一致");
        }
        User user = userMapper.getByUsername(username);
        if(user != null){
            throw new BusinessException("用户名已存在");
        }
        String encodedPassword = passwordEncoder.encode(password);

        userMapper.add(username,encodedPassword);
    }

    @Override
    public String checkUsername(String username) {
        User user = userMapper.getByUsername(username);
        if(user != null){
            return "用户名已经存在";
        }
        return null;
    }
}
